<?php

namespace App\Admin\Controllers;

use App\Admin\Filters\ApiDocumentFilter;
use App\Admin\Models\ApiDocument;
use App\Admin\Models\ApiDocumentCategory;
use Illuminate\Support\Facades\Artisan;

class ApiDocumentController extends Controller
{
    // 某个项目下的所有页面
    const SHOWDOC_INFO_URL = "/server/api/item/info";

    # 在线识别链接
    const API_URL = "http://1.116.83.84:9898/ocr/file";

    public function index(
        ApiDocumentFilter $filter,
        ApiDocument $apiDocument,
        ApiDocumentCategory $apiDocumentCategory
    ) {
        $apiDocuments = ApiDocument::withTrashed()
            ->filter($filter)
            ->get()
            ->toArray();
        $apiDocumentCategories = $apiDocumentCategory->toTree();
        if (env('SHOWDOC_ITEM_ID') && env('SHOWDOC_ITEM_PWD') && env('SHOWDOC_DOMAIN')) {
            $apiDocument->bindApiDocument(
                $apiDocumentCategories, 
                $this->showDocItemInfo(), 
                $apiDocuments, 
                'children'
            );
        }
        return $this->ok($apiDocumentCategories);
    }

    public function format(
        ApiDocumentFilter $filter,
        ApiDocument $apiDocument,
        ApiDocumentCategory $apiDocumentCategory
    ) {
        $apiDocuments = ApiDocument::withTrashed()
            ->filter($filter)
            ->get()
            ->toArray();
        $apiDocumentCategories['info'] = [
            '_postman_id'=>uuid(),
            'name'=>env('APP_NAME'),
            'schema'=>"https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
        ];
        $apiDocumentCategories['item'] = $apiDocumentCategory->toTree();
        $apiDocument->changeKey($apiDocumentCategories['item']);
        $apiDocument->bindApiDocument(
            $apiDocumentCategories['item'], 
            $this->showDocItemInfo(), 
            $apiDocuments, 
            'item'
        );
        return $this->ok($apiDocumentCategories);
    }

    public function truncate()
    {
        // 清空API文档表和API文档分类表
        ApiDocument::truncate();
        ApiDocumentCategory::truncate();
        return $this->noContent();
    }

    public function store()
    {
        // 生成API文档
        $dir = app_path().env('SHOWDOC_APIDOC_DIR');
        $re = Artisan::call("admin:make-apidoc {$dir}");
        if ($re!=1) {
            return $this->error('失败');
        }
    }

    public function showDocItemInfo()
    {
        $data['item_id'] = env('SHOWDOC_ITEM_ID');
        $data['_item_pwd'] = env('SHOWDOC_ITEM_PWD');
       
        $itemRe = json_decode(curl_post(env('SHOWDOC_DOMAIN').self::SHOWDOC_INFO_URL, $data), true);
        
        $pages = [];
        if (isset($itemRe['error_code']) && $itemRe['error_code']!=0) {
            return $pages;
        }
        $apiDocumentCategoryNames = ApiDocumentCategory::where('parent_id','=','0')
            ->pluck('name')
            ->toArray();
        
        foreach ($itemRe['data']['menu']['catalogs'] as $key => $value) {
            if (in_array($value['cat_name'], $apiDocumentCategoryNames)) {
                $this->showdocPages($pages, $value['catalogs'], [$value['cat_name']]);
            }
        }
        return $pages;
    }

    function showdocPages(&$pages, $catalogs, $dirPathArr){
        foreach ($catalogs as $key => $value) {
            if (isset($value['page_id'])) {
                array_push($dirPathArr, $value['page_title']);
                $dirPath = implode('/', $dirPathArr);
                $pages[$dirPath] = env('SHOWDOC_DOMAIN').'/'.env('SHOWDOC_ITEM_ID').'/'.$value['page_id'];
            } elseif (isset($value['pages']) && $value['pages']) {
                array_push($dirPathArr, $value['cat_name']);
                $this->showdocPages($pages, $value['pages'], $dirPathArr);
            }
            array_pop($dirPathArr);
        }
    }
}
